import 'package:backdrop/backdrop.dart';
import 'package:flutter/material.dart';
import 'package:flutter_2b_client/apis/CheckInventoryRecordApi.dart';
import 'package:flutter_2b_client/components/FilterBackLayerLayout.dart';
import 'package:flutter_2b_client/components/LoadingButton.dart';
import 'package:flutter_2b_client/components/PageableQueryFrontLayer.dart';
import 'package:flutter_2b_client/model/NullableLocalDateRange.dart';
import 'package:flutter_2b_client/store/EmployeeAuthorizationStore.dart';
import 'package:flutter_2b_client/utils/MobxHooks.dart';
import 'package:flutter_2b_client/utils/StringUtils.dart';
import 'package:flutter_2b_client/utils/local_datetime.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../components/DateRangeTextField.dart';
import '../components/FormItem.dart';
import '../model/IntIdAndName.dart';
import '../utils/Page.dart';
import '../utils/PagingUtils.dart';

class CheckInventoryRecord extends HookWidget {
  const CheckInventoryRecord({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var pagingController =
        usePagingController<Pageable, QueryCheckInventoryRecordResponse>(
            firstPageKey: Pageable());
    var totalElementsState = useState(0);
    var filterDataState = useState(const QueryCheckInventoryRecordRequest());

    usePagingControllerListener(
        pagingController,
        (pageable) => checkInventoryRecordApi
                .queryCheckInventoryRecords(filterDataState.value, pageable)
                .then((value) {
              totalElementsState.value = value.totalElements;
              return value;
            }),
        (item) => item.id,
        [
          filterDataState.value,
        ]);
    var store = Provider.of<EmployeeAuthorizationStore>(context);
    var me = useObservable(() => store.me);
    return BackdropScaffold(
      backLayerBackgroundColor: Theme.of(context).colorScheme.primaryContainer,
      floatingActionButton: me?.hasAuthority("库存_盘点_盘点") != true
          ? null
          : FloatingActionButton(
              onPressed: () {
                showDialog(
                  context: context,
                  builder: (context) {
                    var textEditingController = TextEditingController();
                    return AlertDialog(
                      content: TextField(
                        controller: textEditingController,
                        decoration: const InputDecoration(label: Text("名称")),
                      ),
                      actions: [
                        TextButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          child: Text(
                            "取消",
                            style: Theme.of(context).textTheme.bodyMedium,
                          ),
                        ),
                        LoadingButton(
                          child: const Text("创建"),
                          onPressed: () async {
                            var response = await checkInventoryRecordApi
                                .createCheckInventoryRecord(
                              CreateCheckInventoryRecordRequest(
                                  name: textEditingController.text.nullIfEmpty),
                            );
                            pagingController.itemList = (pagingController.itemList??[]).toList()
                            ..add(response);

                            if (context.mounted) {
                              Navigator.pop(context);
                              context.push("/checkInventoryRecords/${response.id}");
                            }
                          },
                        ),
                      ],
                    );
                  },
                );
              },
              child: const Icon(Icons.add),
            ),
      appBar: AppBar(
        title: const Text("盘点"),
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
        actions: [
          BackdropToggleButton(
            icon: AnimatedIcons.close_menu,
            color: filterDataState.value.hasAnyFilter()
                ? Theme.of(context).colorScheme.tertiary
                : Theme.of(context).colorScheme.onPrimaryContainer,
          ),
        ],
      ),
      backLayer: _QueryConditionBackLayer(
        onConfirm: (data) {
          filterDataState.value = data;
        },
      ),
      frontLayer: PageableQueryFrontLayer(
        pagingController: pagingController,
        itemBuilder: (context, item, index) => ListTile(
          dense: true,
          onTap: () {
            context.push("/checkInventoryRecords/${item.id}");
          },
          title: Text(item.name),
          subtitle: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(item.createdDateTime.format()),
              Text(item.submittedDateTime == null ? "待提交" : "已提交"),
            ],
          ),
        ),
        resource: "盘点",
      ),
    );
  }
}

class _QueryConditionBackLayer extends HookWidget {
  final void Function(QueryCheckInventoryRecordRequest data) onConfirm;

  const _QueryConditionBackLayer({Key? key, required this.onConfirm})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    var employeesState = useState<List<IntIdAndName>>([]);
    useEffect(() {
      checkInventoryRecordApi
          .getAllCheckInventoryRecordCreatedEmployees()
          .then((value) {
        employeesState.value = value;
      });
      return null;
    }, []);

    var selectableDateRangeState = useState<DateTimeRange?>(null);
    useEffect(() {
      (() async {
        var range = await checkInventoryRecordApi
            .getAllCheckInventoryRecordCreatedDateRange();
        selectableDateRangeState.value = range.toDateTimeRangeOrNull();
      })();
      return null;
    }, []);

    var conditionState = useState(const QueryCheckInventoryRecordRequest());

    return FilterBackLayerLayout(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          FormItem(
            label: "创建人",
            child: DropdownMenu<IntIdAndName>(
              enableFilter: true,
              onSelected: (item) {
                conditionState.value = conditionState.value
                    .copyWith(employeeIds: item == null ? [] : [item.id]);
              },
              enableSearch: true,
              dropdownMenuEntries: employeesState.value
                  .map((e) => DropdownMenuEntry(value: e, label: e.name))
                  .toList(),
            ),
          ),
          FormItem(
            label: "状态",
            child: DropdownMenu<bool?>(
              onSelected: (item) {
                conditionState.value =
                    conditionState.value.copyWith(submitted: item);
              },
              enableSearch: false,
              dropdownMenuEntries: const [
                DropdownMenuEntry(value: null, label: "全部"),
                DropdownMenuEntry(value: false, label: "待提交"),
                DropdownMenuEntry(value: true, label: "已提交")
              ],
            ),
          ),
          FormItem(
            label: "创建日期",
            child: DateRangeTextField(
              range: NullableLocalDateRange(
                start: conditionState.value.startDate,
                end: conditionState.value.endDate,
              ).toDateTimeRangeOrNull(),
              selectableRange: selectableDateRangeState.value ??
                  DateTimeRange(start: DateTime.now(), end: DateTime.now()),
              onChange: (DateTimeRange? range) {
                conditionState.value = conditionState.value.copyWith(
                  startDate: range == null ? null : LocalDate(range.start),
                  endDate: range == null ? null : LocalDate(range.end),
                );
              },
              placeholder: "选择日期范围",
            ),
          ),
        ],
      ),
      onClear: () {
        conditionState.value = const QueryCheckInventoryRecordRequest();
      },
      onConfirm: () {
        onConfirm(conditionState.value);
        Backdrop.of(context).concealBackLayer();
      },
    );
  }
}
